package fmt

import (
	"fmt"
	"io/ioutil"
	"os/exec"
	"src/command"
	"src/utils"
	"strings"
)

func goFmtAll(v ...interface{}) bool {
	cur_dir := utils.GetExePath()
	goFmtDir(cur_dir)

	return true
}

func goFmtDir(dir string) {
	fileinfo, err := ioutil.ReadDir(dir)

	if err != nil {
		fmt.Println("\rreaddir ", dir, " failed ")
		return
	}

	for _, file := range fileinfo {
		fileName := dir + "/" + file.Name()
		if file.IsDir() {
			goFmtDir(fileName)
		} else {
			if strings.HasSuffix(file.Name(), "go") {
				fmt.Println("\rfmt ", fileName)
				cmd := exec.Command("go", "fmt", fileName)
				cmd.Run()
			}
		}
	}
}

func init() {
	ele := command.RegisterElement("fmt", "格式化工具")
	ele.RegisterCmd("gofmt", goFmtAll, "将当前执行程序目录下的所有go文件格式化一下")
}
